package com.ldk.admin.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ldk.framework.entity.Area;
import com.ldk.framework.entity.Companypermit;
import com.ldk.framework.service.IAreaService;
import com.ldk.framework.service.ICompanypermitService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.FORM;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.EncryptUtil;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.AdminUser;
import com.ldk.framework.entity.Role;
import com.ldk.framework.service.IAdminUserService;
import com.ldk.framework.service.IRoleService;

@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController {

	/**
	 * 路由地址
	 */
	private final String route = "admin";
	/**
	 * 模块名称
	 */
	private final String module = "用户";
	
	@Autowired
	private IAdminUserService adminUserService;
	@Autowired
	private IRoleService roleService;
	@Autowired
	private IAreaService areaService;

	@Autowired
	private ICompanypermitService companypermitService;
	
	@RequestMapping("/list")
	//public ModelAndView list(ModelMap map){
	public ModelAndView list(ModelMap map,HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);

		if(this.getRoleId(request) == 6) {
			setLinks(map, "", "", module + "管理", "/" + route + "/list", "", "");
		}else {
			setLinks(map, "", "", module + "管理", "/" + route + "/list", "添加" + module, "/" + route + "/add");
		}

		//操作日志
		//this.insertOplog(request,module+"管理","","","查看",this.getAdminUserName(request).toString(),Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

		if (this.getRoleId(request) == 6) {
			return new ModelAndView("/admin/listadmin_sj");
		} else {
			return new ModelAndView("/admin/listadmin");
		}
	}
	
	@ResponseBody
	@RequestMapping("/getList")
	public LigerUIGridResult<AdminUser> getList(@RequestParam(value="page",required=false,defaultValue="1") int page, 
									            @RequestParam(value="pagesize",required=false,defaultValue="10") int pageSize,
									            @RequestParam(value="userName",required=false,defaultValue="") String userName,
									            HttpServletRequest request)
	{
		int limit = pageSize;
		int offset = (page -1) * pageSize;
		
		AdminUser query = new AdminUser();
		if(!StringUtils.isEmpty(userName)){
			query.setUserName(userName);
		}
		CustomPageable pageable = new CustomPageable(offset, limit);
		Page<AdminUser> result = adminUserService.selectPageList("", query, pageable);

		LigerUIGridResult<AdminUser> grid = new LigerUIGridResult<>();
		grid.Total = result.getTotalElements();
		grid.Rows = result.getContent();
		
		return grid;
	}
	
	@RequestMapping("/add")
	public ModelAndView add(ModelMap map,HttpServletRequest request,
							HttpServletResponse response){

		//session是否过期
		this.isExpired(request,response);

		setLinks(map, module+"管理", "/"+route+"/list", "添加"+module, "/"+route+"/add", "", "");
		setForm(map, "/"+route+"/insert", null);
		
		Role roleQuery = new Role();
		roleQuery.setEnabled(true);
		List<Role> roles = roleService.selectList("", roleQuery);
		map.addAttribute("roles", roles);

		Area areaQuery = new Area();
		List<Area> areas = areaService.selectList("", areaQuery);
		map.addAttribute("areas", areas);

		map.addAttribute("companyList", getCompanyList());
		
		AdminUser model = new AdminUser();
		//System.out.println("userId="+model.getUserId()); //null
		
		return new ModelAndView("/admin/admininfo","model",model);
	}
	
	@RequestMapping("/edit/{userId}")
	public ModelAndView edit(@PathVariable int userId, ModelMap map,HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);

		AdminUser query = new AdminUser();
		query.setUserId(userId);
		
		AdminUser model = adminUserService.selectByKey("", query);
		if(model == null){
			return new ModelAndView("redirect:/"+route+"/list");
		}
		setLinks(map, module+"管理", "/"+route+"/list", "编辑"+module, "/"+route+"/edit/"+userId, "", "");
		setForm(map, "/"+route+"/update", null);
		
		Role roleQuery = new Role();
		roleQuery.setEnabled(true);
		List<Role> roles = roleService.selectList("", roleQuery);
		map.addAttribute("roles", roles);

		Area areaQuery = new Area();
		List<Area> areas = areaService.selectList("", areaQuery);
		map.addAttribute("areas", areas);

		map.addAttribute("companyList", getCompanyList());
		
		return new ModelAndView("/admin/admininfo","model", model);
	}
	
	@RequestMapping("/userRole/{userId}")
	public ModelAndView userRole(@PathVariable int userId, ModelMap map,HttpServletRequest request,
								 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);

		AdminUser query = new AdminUser();
		query.setUserId(userId);
		
		AdminUser model = adminUserService.selectByKey("", query);
		if(model == null){
			return new ModelAndView("redirect:/"+route+"/list");
		}
		setLinks(map, module+"管理", "/"+route+"/list", "设置角色", "/"+route+"/userRole/"+userId, "", "");
		setForm(map, "/"+route+"/setUserRole/"+userId, null);
		
		Role roleQuery = new Role();
		roleQuery.setEnabled(true);
		List<Role> roles = roleService.selectList("", roleQuery);
		map.addAttribute("roles", roles);
		map.addAttribute("userId", userId);
		map.addAttribute("roleId", model.getRoleId());
		
		return new ModelAndView("/admin/adminrole");
	}
	
	@RequestMapping("/setUserRole/{userId}")
	//public ModelAndView setUserRole(@PathVariable int userId, @RequestParam(value="roleId",required=true) int roleId, RedirectAttributes redAttr, ModelMap map)
	public ModelAndView setUserRole(@PathVariable int userId, @RequestParam(value="roleId",required=true) int roleId,
									RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
									HttpServletResponse response)
	{
		//session是否过期
		this.isExpired(request,response);

		ResponseResult rst = new ResponseResult();
		
		if(roleId < 1){
			rst.AddError("设置角色错误");
		}
		else{
			AdminUser model = new AdminUser();
			model.setUserId(userId);
			model.setRoleId(roleId);

			//操作日志
			AdminUser query = new AdminUser();
			query.setUserId(userId);
			AdminUser adminUser = adminUserService.selectByKey("", query);
			this.insertOplog(request,module,"","","为"+adminUser.getUserName()+"设置角色:角色id="+model.getRoleId(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

			int row = adminUserService.updateByKey("", model);
			if(row > 0){
				rst.AddOk("设置用户角色成功");
			}
			else{
				rst.AddOk("设置用户角色失败");
			}
			
		}
		redAttr.addAttribute("userId", userId);
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		
		return new ModelAndView("redirect:/"+route+"/userRole/{userId}");
	}
	
	@RequestMapping("/insert")
	public ModelAndView insert(@ModelAttribute("model") AdminUser model, RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
							   HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);

		ResponseResult rst = new ResponseResult();
		
		try{
			if(model.getPassword() != null && 
			  !StringUtils.isEmpty(model.getPassword())){

				//密码复杂度校验
				/*if (!SystemUtil.validPwd(model.getPassword())) {
					rst.AddError("密码过于简单！请重新输入密码。");
					redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);

					return new ModelAndView("redirect:/"+route+"/add");
				}*/
				//生成新的混淆码
				String salt = String.format("%06d", SystemUtil.generateRandom(999999));
				String textPwd = String.format("%s%s", model.getPassword(), salt);
				//重新加密密码
				String md5Pwd = EncryptUtil.md5(textPwd);
				
				model.setSalt(salt);
				model.setPassword(md5Pwd);
			}
			model.setAddTime(SystemUtil.getAllSeconds());
			model.setLoginIp(request.getRemoteHost());
			model.setLoginTime(SystemUtil.getAllSeconds());

			if(model.getEnabled() == null){
				model.setEnabled(false);
			}

			//操作日志
			this.insertOplog(request,module,"","","添加用户:"+model.getUserName(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

		    int row = adminUserService.insert("", model);
		    if(row > 0){
		    	rst.AddOk("添加用户成功");
		    }
		    else{
		    	rst.AddError("添加用户失败");
		    }
		}
		catch(Exception e){
			System.out.println("出现异常：" + e.getMessage());
			rst.AddError("添加用户失败");
		}
		
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		
		return new ModelAndView("redirect:/"+route+"/add");
	}
	
	@RequestMapping("/update")
	public ModelAndView update(@ModelAttribute("model") AdminUser model, RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
							   HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);

		ResponseResult rst = new ResponseResult();
		
		try{
			//后台不能修改下面的属性
			if(model.getEnabled() == null){
				model.setEnabled(false);
			}

			//密码复杂度校验
			/*if (!SystemUtil.validPwd(model.getPassword())) {
				rst.AddError("密码过于简单！请重新输入密码。");
				redAttr.addAttribute("userId", model.getUserId());
				redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);

				return new ModelAndView("redirect:/"+route+"/edit/{userId}");
			}*/
			
			if(model.getPassword() != null && 
			  !StringUtils.isEmpty(model.getPassword())){
				//生成新的混淆码
				String salt = String.format("%06d", SystemUtil.generateRandom(999999));
				String textPwd = String.format("%s%s", model.getPassword(), salt);
				//重新加密密码
				String md5Pwd = EncryptUtil.md5(textPwd);
				
				model.setSalt(salt);
				model.setPassword(md5Pwd);
			}

			//操作日志
			this.insertOplog(request,module,"","","修改用户:"+model.getUserName(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

			int row = adminUserService.updateByKey("", model);
		    if(row > 0){
		    	rst.AddOk("修改用户成功");
		    }
		    else{
		    	rst.AddError("修改用户失败");
		    }
		}
		catch(Exception e){
			rst.AddError("修改用户失败，失败原因："+e.getMessage());
		}

		redAttr.addAttribute("userId", model.getUserId());
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		
		return new ModelAndView("redirect:/"+route+"/edit/{userId}");
	}
	
	@ResponseBody
	@RequestMapping("/remove/{userId}")
	public ResponseResult remove(@PathVariable int userId, HttpServletRequest request,
								 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		
		ResponseResult rst = new ResponseResult();
		if(userId < 1)
		{
			rst.AddError("删除用户错误");
			return rst;
		}
		AdminUser query = new AdminUser();
		query.setUserId(userId);
		
		AdminUser adminUser = adminUserService.selectByKey("", query);
		if(adminUser == null){
			rst.AddError("用户不存在");
			return rst;
		}
		if(adminUser.getUserName().equalsIgnoreCase("admin")){
			rst.AddError("超级管理员不允许删除");
			return rst;
		}

		//操作日志
		this.insertOplog(request,module,"","","删除用户:"+adminUser.getUserName(),this.getAdminUserName(request).toString(),
				Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

		int row  = adminUserService.deleteByKey("", query);
		if(row > 0){
			rst.AddOk("删除用户成功");
		}
		else{
			rst.AddError("删除用户失败");
		}
		
		return rst;
	}
	
	/**
	 * 检查后台管理员用户名是否已经存在
	 * @param userName
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/checkUserName")
	public ResponseResult checkUserName(@RequestParam(value="userId",required=true,defaultValue="0") int userId,
								@RequestParam(value="userName",required=true,defaultValue="") String userName){
		ResponseResult rst = new ResponseResult();
		if(StringUtils.isEmpty(userName)){
			rst.AddError("管理员名称不能为空");
			return rst;
		}
		AdminUser query = new AdminUser();
		query.setUserName(userName);
		
		AdminUser admin = adminUserService.selectOne("", query);
		if(admin != null){
			if(userId > 0 && admin.getUserId() == userId){
				rst.AddOk("");
			}
			else{
				rst.AddError("管理员名称已经存在");
			}
		}
		else{
			rst.AddOk("");
		}
		return rst;
	}
	
	/**
	 * 修改用户密码
	 * @param userId
	 * @param map
	 * @return
	 */
	@RequestMapping("/userPassowd/{userId}")
	public ModelAndView userPassowd(@PathVariable int userId, ModelMap map,HttpServletRequest request,
									HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);

		setLinks(map, "", "", "修改用户密码", "/"+route+"/userPassowd/"+userId, "", "");
		setForm(map, "/"+route+"/submitPassowd/"+userId, null);
		map.addAttribute("userId", userId);
		
		return new ModelAndView("/admin/adminpassword");
	}
	/**
	 * 提交用户密码
	 * @param userId
	 * @param map
	 * @return
	 */
	@RequestMapping("/submitPassowd/{userId}")
	public ModelAndView submitPassowd(@PathVariable int userId, 
									  @RequestParam(value="oldpass",required=true,defaultValue="") String oldpass,
									  @RequestParam(value="newpass",required=true,defaultValue="") String newpass,
									  @RequestParam(value="checkpass",required=true,defaultValue="") String checkpass,
									  RedirectAttributes redAttr,
									  ModelMap map,HttpServletRequest request,
									  HttpServletResponse response)
	{
		//session是否过期
		this.isExpired(request,response);

		ResponseResult rst = new ResponseResult();
		redAttr.addAttribute("userId", userId);
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		if(StringUtils.isEmpty(oldpass)){
			rst.AddError("原始密码不能为空");
			return new ModelAndView("redirect:/admin/userPassowd/{userId}");
		}
		if(StringUtils.isEmpty(newpass)){
			rst.AddError("新密码不能为空");
			return new ModelAndView("redirect:/admin/userPassowd/{userId}");
		}
		if(!newpass.equalsIgnoreCase(checkpass)){
			rst.AddError("确认密码和新密码不一致");
			return new ModelAndView("redirect:/admin/userPassowd/{userId}");
		}
		//判断原始密码对不对
		AdminUser query = new AdminUser();
		query.setUserId(userId);
		
		AdminUser adminUser = adminUserService.selectByKey("", query);
		if(adminUser == null){
			rst.AddError("用户不存在");
			return new ModelAndView("redirect:/admin/userPassowd/{userId}");
		}
		/*if(!adminUser.getPassword().equalsIgnoreCase(EncryptUtil.md5(oldpass+adminUser.getSalt()))){
			rst.AddError("用户原始密码错误");
			return new ModelAndView("redirect:/admin/userPassowd/{userId}");
		}*/

		//密码复杂度校验
		if (!SystemUtil.validPwd(newpass)) {
			rst.AddError("密码过于简单！请重新输入密码。");
			redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);

			return new ModelAndView("redirect:/admin/userPassowd/{userId}");
		}
		
		//生成新的混淆码
		String salt = String.format("%06d", SystemUtil.generateRandom(999999));
		String textPwd = String.format("%s%s", newpass, salt);
		//重新加密密码
		String md5Pwd = EncryptUtil.md5(textPwd);
		
		try{
			AdminUser entity = new AdminUser();
			entity.setUserId(userId);
			entity.setSalt(salt);
			entity.setPassword(md5Pwd);
			int row = adminUserService.updateByKey("", entity);
			if(row > 0){
				rst.AddOk("修改密码成功");
			}
			else{
				rst.AddError("修改密码失败");
			}
			
		}catch(Exception e){
			rst.AddError("修改密码失败");
		}
		
		return new ModelAndView("redirect:/admin/userPassowd/{userId}");
	}
	
	
	/**
	 * 用户地区
	 * @param userId
	 * @param map
	 * @return
	 */
	@RequestMapping("/adminRegion/{userId}")
	public ModelAndView adminRegion(@PathVariable int userId, ModelMap map,HttpServletRequest request,
									HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);

		setLinks(map, module+"管理", "/"+route+"/list", "设置用户权限", "/"+route+"/adminRegion/"+userId, "", "");
		map.addAttribute("userId", userId);
		
		return new ModelAndView("/admin/adminregion");
	}


	/**
	 * 获取分公司列表
	 *
	 * @return
	 */
	private List<Companypermit> getCompanyList() {
		Companypermit query = new Companypermit();
		query.setEnabled(true);

		return companypermitService.selectList("", query);
	}
}
